package services

import (
	"context"
	"fmt"
	"wxapi/internal/svc"
	"wxapi/models"
)

func GetStoreList(ctx context.Context, svc *svc.ServiceContext, lat, lon float64, province, city, area string, page, pageSize int64) ([]*models.Store, error) {
	list := make([]*models.Store, 0)

	where := "state != 0"
	if province != "" {
		where += fmt.Sprintf(" and province = '%s'", province)
	}
	if city != "" {
		where += fmt.Sprintf(" and city = '%s'", city)
	}
	if area != "" {
		where += fmt.Sprintf(" and area = '%s'", area)
	}

	svc.Mysql.Model(&models.Store{}).Select("*,  6371 * 2 * ASIN(SQRT(POW(SIN(RADIANS((store_location_lat - " + fmt.Sprintf("%f", lat) +
		") / 2)), 2) +COS(RADIANS(" + fmt.Sprintf("%f", lat) +
		")) * COS(RADIANS(store_location_lat)) *POW(SIN(RADIANS((store_location_lon - " +
		fmt.Sprintf("%f", lon) + ") / 2)), 2) ) ) AS distance").Where(where).Offset(int(page * pageSize)).Limit(int(pageSize)).Order("distance, `order`").Find(&list)

	return list, nil
}

func GetStoreListById(ctx context.Context, svc *svc.ServiceContext, storeId int64, lat, lon float64) (*models.Store, error) {
	store := &models.Store{}
	svc.Mysql.Model(&models.Store{}).Preload("OtherInfo").Where("id = ? AND state = 100", storeId).First(&store)

	return store, nil
}
